package com.xyoto.community.task;

import com.xyoto.community.cache.CacheInstruction;
import com.xyoto.community.entity.main.FansWeekIncrement;
import com.xyoto.community.mapper.main.FansWeekIncrementMapper;
import com.xyoto.community.utils.RedisCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Author: 廖振辉
 * Date: 2022/2/19
 * Description: 粉丝周榜情况，并持久化到数据库
 */

@Component
@Slf4j
public class FansWeekIncrementRecordTask {

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Autowired
    private FansWeekIncrementMapper fansWeekIncrementMapper;


    /**
     * 每周一凌晨0点执行一次
     */
    @Scheduled(cron = "0 0 0 ? * 2")
    public void clearFansWeekIncrementRankAndRecordToDB(){
        // 获取出粉丝增长周榜信息
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisCommonUtils.rangeByZSetWithScore(CacheInstruction.FANS_WEEK_INCREMENT, 0, -1);

        List<FansWeekIncrement> fansWeekIncrementList = new ArrayList<>();

        for (ZSetOperations.TypedTuple<Object> typedTuple : typedTuples) {
//            Assert.notNull(typedTuple,"转换粉丝周榜信息是发送错误");
            Double score = typedTuple.getScore();
            Integer userId = (Integer) typedTuple.getValue();

            // 粉丝增长量置0
            redisCommonUtils.zSet(CacheInstruction.FANS_WEEK_INCREMENT,userId,0.0);

            FansWeekIncrement fansWeekIncrement = new FansWeekIncrement(userId, score.intValue());


            fansWeekIncrementList.add(fansWeekIncrement);
        }

        // 持久化到数据库
        for (FansWeekIncrement fansWeekIncrement : fansWeekIncrementList) {
            fansWeekIncrementMapper.insert(fansWeekIncrement);
        }
        log.info("周榜信息已重置，并已记录到数据库");
    }
}
